<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\api\controller\wechat;

use buwang\base\BaseController;
use buwang\facade\WechatMp;
use app\common\model\Member;
use app\common\model\SystemWeb;
use buwang\service\UserService;
use Exception;
use filter\Inspect;
use think\facade\Cookie;

/**
 *  发起微信授权
 */
class WechatAccount extends BaseController
{

    //授权回调
    public function index()
    {
        try {
            $app = WechatMp::official();
            $app->server->push(function ($message) {
                switch ($message['MsgType']) {
                    case 'event':
                        $open_id['appid'] = Inspect::filter_escape($message['FromUserName']);  //openid
                        if ($message['Event'] == 'subscribe' || $message['Event'] == 'SCAN') { //关注|扫描带参数二维码事件
                            $member = Member::where(['openid' => $open_id['appid']])->field('openid')->find();
                            if ($member) {
                                $member->ticket = Inspect::filter_escape($message['Ticket']);  //Ticket
                                $member->save();
                                return '你好,你刚刚登录了「' . bw_config('web_config.web_name') . '」';
                            } else {
                                //创建用户
                                $rdm_code = get_num_code(6);
                                $data['appid'] = $open_id['appid'];
                                $data['ticket'] = Inspect::filter_escape($message['Ticket']);
                                $data['username'] = 'mp' . $rdm_code;
                                $data['password'] = password_hash(md5($rdm_code), PASSWORD_DEFAULT);
                                $data['safe_password'] = password_hash(md5('123456'), PASSWORD_DEFAULT);
                                $data['login_time'] = time();
                                $data['login_ip'] = request()->ip();
                                $data['update_time'] = time();
                                $data['create_time'] = time();
                                Member::create($data);
                                return '你好,你刚刚注册了「' . bw_config('web_config.web_name') . '」帐号';
                            }
                        }
                        break;
                    default:
                        return '';
                        break;
                }
            });
            $response = $app->server->serve();
            return $response->send();
        } catch (Exception $e) {
            return $this->error('授权失败');
        }
    }

    /**
     *  生成登录二维码
     */
    public function createScanCode()
    {
        $scan = bw_config('scan');
        if($scan && !$scan['qrcode_login']) return $this->error('二维码登录注册通道关闭');
        try {
            $rel = WechatMp::official()->qrcode->temporary('scan_login', 6 * 24 * 3600);
            Cookie::set('login_ticket', $rel['ticket'], $rel['expire_seconds']);  //记录二维码ticket
            return $this->success('成功', ['url' => $rel['url']]);
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     *检查登录状态
     */
    public function getLoginState()
    {
        if (Cookie::has('login_ticket')) {
            $ticket = Cookie::get('login_ticket');
            $member = Member::where(['ticket' => $ticket])->field('id,username,openid,ticket')->find();
            if ($member) {
                $member->ticket = null;  //Ticket
                $member->save();
                //登录处理
                $rs = UserService::loginMember($member, true);
                if (!$rs['rs']) return $this->error($rs['error']);
                $rs['rs']['session_id'] = get_session_id();
                $rs['rs']['url'] = '/manage/member/index';

                Cookie::delete('login_ticket');
                return $this->success('成功', $rs['rs'], 400200);
            }
        }
        return $this->error('尚未登录');
    }
}